import { getLayoutProps } from "@/common/layout/getProps";
import { ProForm } from "@/components/ProForm";
import { DownloadOutlined, EditOutlined, ExportOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Button, Col,
  DatePicker,
  Form,
  Input, message,
  Modal,
  Row,
  Space,
  Table,
  Pagination,
  InputNumber,
  type TableColumnsType,
  type TableProps
} from "antd";
import { type Key, useState,useEffect } from "react";
import { http } from "@/utils/request";

type TableDataType = {
  id: string;
  deptName: string;
  name: string;
  post: string;
  rank: string;
  grade: string;
  performanceCoefficient: string;
  performanceBonusBase: string;
  strategicPerformanceScore: string;
  strategicPerformanceCoefficient: string;
  departmentPositionPerformanceScore: string;
  positionPerformanceCoefficient: string;
  performanceBonus: string;
  adjustment: string;
  efficiencyAdjustment: string;
  strategicPositionPerformanceBase: string;
  centralAwardScore: string;
  centralPositionPerformanceRewardAmount: string;
  commendation: string;
  payrollPerformanceBonus: string;
}

type TableRowSelection<T> = TableProps<T>["rowSelection"];

const  EmployeePerformanceCalculations = () => {
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});
  const [list, setList] = useState([]);
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
  const [open, setOpen] = useState<boolean>(false);
  const [id,setId] = useState();
  const columns: TableColumnsType<TableDataType> = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text, _record, index) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "部门",
      fixed: "left",
      dataIndex: "deptName"
    },
    {
      align: "center",
      title: "姓名",
      fixed: "left",
      width: 80,
      dataIndex: "name"
    },
    {
      align: "center",
      title: "岗位",
      fixed: "left",
      width: 100,
      dataIndex: "post"
    },
    {
      align: "center",
      title: "职级",
      dataIndex: "rank"
    },
    {
      align: "center",
      title: "档级",
      dataIndex: "grade"
    },
    {
      align: "center",
      title: "绩效系数",
      dataIndex: "performanceCoefficient"
    },
    {
      align: "center",
      title: "绩效奖基数",
      dataIndex: "performanceBonusBase"
    },
    {
      align: "center",
      title: "战略绩效评分",
      dataIndex: "strategicPerformanceScore"
    },
    {
      align: "center",
      title: "战略绩效考评系数",
      dataIndex: "strategicPerformanceCoefficient"
    },
    {
      align: "center",
      title: "部门岗位绩效考评分数",
      dataIndex: "departmentPositionPerformanceScore"
    },
    {
      align: "center",
      title: "岗位绩效考评系数",
      dataIndex: "positionPerformanceCoefficient"
    },
    {
      align: "center",
      title: "绩效奖金",
      dataIndex: "performanceBonus"
    },
    {
      align: "center",
      title: "调整",
      dataIndex: "adjustment"
    },
    {
      align: "center",
      title: "效益调节",
      dataIndex: "efficiencyAdjustment"
    },
    {
      align: "center",
      title: "战略绩效、岗位绩效后基数",
      dataIndex: "strategicPositionPerformanceBase"
    },
    {
      align: "center",
      title: "中心奖励分数",
      dataIndex: "centralAwardScore"
    },
    {
      align: "center",
      title: "中心岗位绩效奖励金额",
      dataIndex: "centralPositionPerformanceRewardAmount"
    },
    {
      align: "center",
      title: "嘉奖",
      dataIndex: "commendation"
    },
    {
      align: "center",
      title: "工资单绩效奖",
      dataIndex: "payrollPerformanceBonus"
    }
  ]

  const onSelectChange = (keys: Key[]) => {
    setSelectedRowKeys(keys)
  }

  const rowSelection: TableRowSelection<TableDataType> = {
    selectedRowKeys,
    onChange: onSelectChange
  }

  const handleOk = async() => {
    try {
      const values = await editForm.validateFields();
      // 校验成功，执行保存操作并关闭Modal
      editSave(values);
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const editSave = async(formData:object) => {
    try {
      formData.userName = formData.name
      const res = await http.put({
        url:'/PmPerformanceCalculate/update',
        data:{calculateId:id,...formData},
      })
      if(res.code == 200){
        message.success('员工绩效计算修改成功!');
        setOpen(false);
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const handleCancel = () => {
    setOpen(false);
  }
  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }

  //查询接口
  const getList = async() =>{
    try {
      const res = await http.get({
        url:'/PmPerformanceCalculate/qryList',
        params:{
          date:form.getFieldValue('date'),
          userName:form.getFieldValue('userName'),
          post:form.getFieldValue('post'),
          deptId:form.getFieldValue('deptId'),
          pageNum:pageNum,
          pageSize:pageSize,
        }
      })
      setList(res.rows);
      setTotal(res.total);
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  useEffect(()=>{
    getList();
  },[pageNum,pageSize])
  
  return (
    <PageContainer>
      <ProForm form={form} layout={'inline'} onSearch={getList} onReset={getList}>
        <Form.Item
          label={'日期'}
          name="date"
        >
          <DatePicker />
        </Form.Item>
        <Form.Item
          label={'姓名'}
          name="userName"
        >
          <Input placeholder="请输入姓名" />
        </Form.Item>
        <Form.Item
          label={'岗位'}
          name="post"
        >
          <Input placeholder="请输入岗位" />
        </Form.Item>
        <Form.Item
          label={'部门'}
          name="deptId"
        >
          <Input placeholder="请输入部门" />
        </Form.Item>
      </ProForm>

      <Row className={'mb-[20px]'}>
        <Space>
          <Button type={'primary'} icon={<DownloadOutlined />}>导入Excel</Button>
          <Button type={'primary'} icon={<ExportOutlined />}>导出Excel</Button>
          <Button disabled={selectedRowKeys.length !== 1} type={'primary'} icon={<EditOutlined />} onClick={() => {
            const editData = list.find(t => t.id == selectedRowKeys[0])!
            setCurrentEdit(editData);
            setId(selectedRowKeys[0]);
            setTimeout(() => {
              
              setOpen(true);
            }, 1000);
          }}>编辑绩效</Button>
        </Space>
      </Row>

      <Table
        scroll={{ x: 1800 }}
        dataSource={list}
        columns={columns}
        rowKey={(record) => `${record.id}`}
        pagination={false}
        rowSelection={rowSelection}
      ></Table>
      <Pagination
        className={'m-[20px] text-end'}
        current={pageNum}
        pageSize={pageSize}
        total={total}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条`}
        onChange={changePagination}
      />

      <Modal
        width={'50%'}
        open={open}
        title={`${JSON.stringify(currentEdit) === "{}" ? "新增" : "编辑"}考核计算公式配置`}
        afterClose={() => {
          setCurrentEdit({});
          editForm.resetFields();
        }}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={'提交'}
        cancelText={'取消'}
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <OkBtn />
          </>
        )}
      >
        <Form form={editForm} initialValues={currentEdit} labelCol={{span: 6}} labelAlign={'left'} labelWrap>
          <Row>
            <Col span={11}>
              <Form.Item
                label={'部门'}
                name={'deptName'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'姓名'}
                name={'name'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'岗位'}
                name={'post'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'职级'}
                name={'rank'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'档级'}
                name={'grade'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'绩效系数'}
                name={'performanceCoefficient'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
              <Form.Item
                label={'绩效奖基数'}
                name={'performanceBonusBase'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
              <Form.Item
                label={'战略绩效评分'}
                name={'strategicPerformanceScore'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
              <Form.Item
                label={'战略绩效考评系数'}
                name={'strategicPerformanceCoefficient'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
              <Form.Item
                label={'工资单绩效奖'}
                name={'payrollPerformanceBonus'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"} disabled></InputNumber>
              </Form.Item>
            </Col>
            <Col span={11} offset={2}>
              <Form.Item
                label={'部门岗位绩效考评分数'}
                name={'departmentPositionPerformanceScore'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
              <Form.Item
                label={'岗位绩效考评系数'}
                name={'positionPerformanceCoefficient'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"} disabled></InputNumber>
              </Form.Item>
              <Form.Item
                label={'绩效奖金'}
                name={'performanceBonus'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"} disabled></InputNumber>
              </Form.Item>
              <Form.Item
                label={'调整'}
                name={'adjustment'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
              <Form.Item
                label={'效益调节'}
                name={'efficiencyAdjustment'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
              <Form.Item
                label={'战略绩效、岗位绩效后基数'}
                name={'strategicPositionPerformanceBase'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"} disabled></InputNumber>
              </Form.Item>
              <Form.Item
                label={'中心奖励分数'}
                name={'centralAwardScore'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
              <Form.Item
                label={'中心岗位绩效奖励金额'}
                name={'centralPositionPerformanceRewardAmount'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"} disabled></InputNumber>
              </Form.Item>
              <Form.Item
                label={'嘉奖'}
                name={'commendation'}
              >
                <InputNumber className={'w-full'} placeholder={"请输入"}></InputNumber>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </PageContainer>
  )
}

export const getServerSideProps = getLayoutProps;
export default EmployeePerformanceCalculations;
